package com.easytouch.core.task;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by gulin on 2017/8/18.
 */

public class TaskThreadPool {

    private static ExecutorService executorService = Executors.newCachedThreadPool();
    private static LinkedList<String> identifierList = new LinkedList<String>();

    public static synchronized boolean addIdentifier(final String pIdentifier)
    {
        if(pIdentifier == null)
            return false;
        for (int i = 0;i < identifierList.size();i++)
        {
            String identifier = identifierList.get(i);
            if(pIdentifier.equals(identifier))
            {
                return false;
            }
        }
        identifierList.add(pIdentifier);
        return true;
    }

    public static synchronized void removeIdentifier(final String pIdentifier)
    {
        for (int i = 0;i < identifierList.size();i++)
        {
            String identifier = identifierList.get(i);
            if(pIdentifier.equals(identifier))
            {
                identifierList.remove(i);
                break;
            }
        }
    }

    public static void addTaskAndRun(final Task pTask)
    {
        if(pTask == null)
            return;
        if(!addIdentifier(pTask.getIdentifier()))
            return;
        executorService.execute(pTask);
    }
}
